# BSD3.0
# cili@163.com

from socket import gethostbyname, gethostname
import tkinter as tk
from tkinter.ttk import Label,Entry,Radiobutton
from http.server import BaseHTTPRequestHandler
import socketserver
import socket
import threading

class MyTCPServer:
    def __init__(self,port,request_handler):
        self.server_thread = None
        for tport in range(port,60000):
            try:
                self.server = socketserver.ThreadingTCPServer(('', tport), request_handler)
                self.port = tport
                break
            except socket.error as e:
                pass
        self.server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    def start(self):
        if self.server:
            server_thread = threading.Thread(target=self.server.serve_forever)
            server_thread.daemon = True
            server_thread.start()

    def stop(self):
        if self.server is not None:
            stop_thread = threading.Thread(target=self.stop_server_thread)
            stop_thread.start()

    def stop_server_thread(self):
        if self.server is not None:
            self.server.shutdown()
            self.server.server_close()
            if self.server_thread: self.server_thread.join(2)
            self.server_thread = None
            self.server = None

root = tk.Tk()
encoding_var = tk.StringVar()
message_var = tk.StringVar()
url_var = tk.StringVar()


class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        encoding = encoding_var.get()
        self.send_header('Content-type', 'text/html; charset=' + encoding)
        self.end_headers()
        web_message = message_var.get()
        message = web_message.encode(encoding)
        self.wfile.write(message)


class WebServerApp:
    def __init__(self, root):
        self.root = root
        self.tips = ['利用访问地址即可访问网站。', '可尝试修改编码和内容。', '可尝试把转换后的图像编码复制进来']

        self.port = tk.IntVar(value=8080)
        self.ip = gethostbyname(gethostname())
        self.server = MyTCPServer(self.port.get(), MyHandler)
        self.server.start()
        self.port.set(self.server.port)

        self.root.title("Web服务器")
        self.root.resizable(False, False)

        self.create_widgets()
        self.center_windows()
        #self.create_tips(5)

        self.message_entry.focus()
        self.message_entry.select_range(0, tk.END)

    def create_widgets(self):
        Label(self.root, text="IP地址：", anchor='e').grid(row=0, column=0, sticky="e", padx=5, pady=5)
        Label(self.root, text=self.ip).grid(row=0, column=1, columnspan=2, sticky="w", padx=5, pady=5)

        Label(self.root, text="服务端口：", anchor='e').grid(row=1, column=0, sticky="e", padx=5, pady=5)
        Label(self.root, textvariable=self.port).grid(row=1, column=1, columnspan=2, sticky="w", padx=5, pady=5)

        self.status_label = Label(self.root, text="编码：", anchor='e')
        self.status_label.grid(row=2, column=0, sticky="e", padx=5, pady=5)

        encoding_var.set("utf-8")
        Radiobutton(root, text="UTF-8", variable=encoding_var, value="utf-8").grid(row=2, column=1, sticky="w")
        Radiobutton(root, text="GBK", variable=encoding_var, value="gbk").grid(row=2, column=2, sticky="w")

        Label(self.root, text="内容：", anchor='e').grid(row=3, column=0, sticky="e", padx=5, pady=5)
        message_var.set("我爱你中国")
        self.message_entry = Entry(root, textvariable=message_var, width=50)
        self.message_entry.grid(row=3, column=1, columnspan=2, padx=5, pady=5)

        tk.Label(self.root, text="访问：", anchor='e').grid(row=4, column=0, sticky="e", padx=5, pady=5)
        self.url_text = Entry(self.root)
        self.url_text.insert(tk.END, f"http://{self.ip}:{self.port.get()}")
        self.url_text.state(['readonly'])
        self.url_text.grid(row=4, column=1, columnspan=2, sticky="ew", padx=5, pady=5)

    def create_tips(self, index):
        [tk.Label(self.root, text=f'{i + 1}. {value}', anchor='e').grid(row=index + i, column=0, columnspan=3,
            sticky="w", padx=5, pady=5) for i, value in enumerate(self.tips)]

    def center_windows(self):
        self.root.update()
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_width = self.root.winfo_width()
        window_height = self.root.winfo_height()
        x = int((screen_width / 2) - (window_width / 2))
        y = int((screen_height / 2) - (window_height / 2))
        self.root.geometry("+{}+{}".format(x, y))


if __name__ == "__main__":
    app = WebServerApp(root)
    root.mainloop()
